package com.learn.hibernatevalidator.chapter12.context;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.constraints.Future;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import java.time.Instant;

/**
 * @author: liyf
 * @create: 2025-02-05 21:24
 **/
public class MyFutureValidator implements ConstraintValidator<Future, Instant> {

    @Override
    public void initialize(Future constraintAnnotation) {
    }

    @Override
    public boolean isValid(Instant value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }

        HibernateConstraintValidatorContext hibernateContext = context.unwrap(
                HibernateConstraintValidatorContext.class
        );

        Instant now = Instant.now(context.getClockProvider().getClock());

        if (!value.isAfter(now)) {
            hibernateContext.disableDefaultConstraintViolation();
            hibernateContext
                    .addExpressionVariable("now", now)
                    .buildConstraintViolationWithTemplate("Must be after ${now}")
                    .addConstraintViolation();

            return false;
        }

        return true;
    }
}
